package com.example.controller;

import com.example.dto.WebSocketMessage;
import com.example.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.stereotype.Controller;
import lombok.extern.slf4j.Slf4j;
import java.security.Principal;

/**
 * WebSocket控制器
 * 处理WebSocket消息
 */
@Controller
@Slf4j
public class WebSocketController {
    
    @Autowired
    private WebSocketService webSocketService;
    
    /**
     * 处理客户端发送的消息
     */
    @MessageMapping("/sendMessage")
    @SendTo("/topic/notifications")
    public WebSocketMessage sendMessage(@Payload WebSocketMessage message) {
        log.info("收到客户端消息: {}", message.getTitle());
        return message;
    }
    
    /**
     * 处理私人消息
     */
    @MessageMapping("/sendPrivateMessage")
    @SendToUser("/queue/notifications")
    public WebSocketMessage sendPrivateMessage(@Payload WebSocketMessage message, Principal principal) {
        log.info("收到私人消息: {} from {}", message.getTitle(), principal.getName());
        return message;
    }
    
    /**
     * 处理心跳消息
     */
    @MessageMapping("/heartbeat")
    public void heartbeat(Principal principal) {
        if (principal != null) {
            log.debug("收到用户 {} 的心跳", principal.getName());
        }
    }
}
